package com.kadron.jobs;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import javax.transaction.UserTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.transaction.Transaction;

import com.kadron.common.KUtil;
import com.kadron.dao.KNewsletterDAO;
import com.kadron.dao.KUserDAO;
import com.kadron.entity.NewsLetter;
import com.kadron.entity.User;
import com.kadron.entity.UserNewsletter;
import com.kadron.exceptions.KVersionException;
import com.kadron.mail.KMailService;
import com.kadron.transaction.KTx;

@AutoCreate
@Name(KNewsletterJob.K_NAME)
@Scope(ScopeType.EVENT)
public class KNewsletterJob extends TimerTask {
	
	public static final String K_NAME = "KNewsletterJob";
	protected static final String INFO_MESASGE = "RUN job"+K_NAME;
	
	private static final Log log = LogFactory.getLog(KNewsletterJob.class);

	@In
	private KNewsletterDAO newsletterDAO;
	@In
	private KUserDAO userDAO;
	
	@Override
	public void run() {
		if (log.isInfoEnabled()) {
			log.info(INFO_MESASGE);
		}
		Date moment = KUtil.getMoment();
		List<NewsLetter> letters = newsletterDAO.getNewsletters(moment);
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			for (NewsLetter nl : letters) {
				List<User> users = userDAO.getNewsletterUsers(nl.getId());
				for (User user : users) {
					try {
						KMailService.sendNewsletter(user, nl);
						UserNewsletter un = new UserNewsletter(user.getId(), nl.getId());
						userDAO.update(un);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				nl.setProcessed(true);
				try {
					userDAO.updateVersioned(nl);
					KTx.commit(transaction);
					KTx.begin(transaction);
				} catch (KVersionException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			KTx.rollback(transaction);
			KTx.begin(transaction);
		}
	}

	
	
}
